package info.xinfu.carban.fragment;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.hui.util.log.LogUtils;
import com.vondear.rxtools.RxNetUtils;
import com.xinfu.xrecyclerview.XRecyclerView;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.Unbinder;
import info.xinfu.carban.Event_Send_Message;
import info.xinfu.carban.R;
import info.xinfu.carban.adapter.MessageListAdapter;
import info.xinfu.carban.adapter.RecordListAdapter;
import info.xinfu.carban.base.BaseFragment;
import info.xinfu.carban.entity.MessageObserver;
import info.xinfu.carban.entity.RecordEntity;
import info.xinfu.carban.utils.Constants;
import info.xinfu.carban.utils.DividerItemDecoration;
import info.xinfu.carban.utils.SPUtils;
import io.realm.Realm;
import io.realm.RealmObject;
import io.realm.RealmResults;
import okhttp3.Call;

/**
 * @author clare
 * 车辆进出记录查询
 */
public class RecordListFragment extends BaseFragment {
    @BindView(R.id.xrv_month_rank)
    XRecyclerView mRecyclerView;
    @BindView(R.id.all_num)
    TextView allNum;
    @BindView(R.id.all_on)
    TextView allOn;
    @BindView(R.id.all_off)
    TextView allOff;
    @BindView(R.id.btn_bottom)
    Button btnBottom;
    Unbinder unbinder;
    @BindView(R.id.top_ll)
    LinearLayout topLl;
    private int mYear;
    private boolean isFirstEntry = false;
    private int all_num, all_on, all_off;
    private String mDate = "";
    //当前页码
    private int pageNo = 1;
    private boolean isLastPage = false;
    Realm mRealm;

    List<RecordEntity> mRecordData = new ArrayList<RecordEntity>();
    private RecordListAdapter mAdapterRecord;
    public static RecordListFragment getInstance(String type) {
        RecordListFragment fragment1 = new RecordListFragment();
        Bundle bdl = new Bundle();
        bdl.putString("type", type);
        fragment1.setArguments(bdl);
        return fragment1;
    }

    @Override
    protected void initListener() {

    }

    @Override
    protected void initView() {
      //  mRealm = Realm.getDefaultInstance();
        EventBus.getDefault().register(this);
        initRecyclerView();
    }

    @Override
    protected void initData() {

//        getData();

    }

    @Override
    protected int getRootViewId() {
        return R.layout.fragment_seller_list;
    }

    private void refreshNumView() {
     /*   all_on = all_off = all_num = 0;
        for (MessageObserver datum : mData) {
            if(datum.getStatus() == 1){
                all_on ++;
            } else {
                all_off ++;
            }
            all_num ++;
        }
        allNum.setText("监控总数:"+all_num);
        allOn.setText("上架数:"+all_on);
        allOff.setText("下架数:"+all_off);*/
    }

    private void initRecyclerView() {
        topLl.setVisibility(View.GONE);
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(context);
        //一个小问题，触摸到RecyclerView的时候滑动还有些粘连的感觉
        linearLayoutManager.setSmoothScrollbarEnabled(true);
        mRecyclerView.setLayoutManager(linearLayoutManager);

        mRecyclerView.setPullRefreshEnabled(true);
        mRecyclerView.addItemDecoration(new DividerItemDecoration(context));
        mRecyclerView.setHasFixedSize(true);
        final String uname = SPUtils.getString(Constants.username, "");
//        RealmResults<RecordEntity> recordEntities = mRealm.where(RecordEntity.class).equalTo("name",uname).findAll();
//        mRecordData = recordEntities;

        mRecordData = JSON.parseArray( mCache.getAsString(uname),RecordEntity.class);

        mAdapterRecord = new RecordListAdapter
                (R.layout.item_record_content, mRecordData);
        mRecyclerView.setAdapter(mAdapterRecord);
        mRecyclerView.setLoadingMoreEnabled(false);
        mAdapterRecord.setEnableLoadMore(false);
/*
        mRecyclerView.setLoadingListener(new XRecyclerView.LoadingListener() {
            @Override
            public void onRefresh() {
                getData();
            }

            @Override
            public void onLoadMore() {

            }
        });*/
    }

    protected void deleteMobileConfirm(final int id) {
        new AlertDialog.Builder(context).setTitle("提示：")
                .setMessage("确定停止监控该商品吗？")
                .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                    }
                }).setPositiveButton("确定", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                deleteObserver(id);
                dialog.dismiss();

            }
        }).show();


    }

  /*  private void getData() {
        final String uname = SPUtils.getString(Constants.username, "");
        if (RxNetUtils.isAvailable(context)) {
            String akey = SPUtils.getString(Constants.accessKey, "");
            OkHttpUtils.post().url(Constants.getsmssendlist)
                    .addParams(Constants.username, uname)

                    .build().execute(new StringCallback() {
                @Override
                public void onError(Call call, Exception e, int id) {
                    LogUtils.e(e.getMessage());

                }

                @Override
                public void onResponse(String response, int id) {
                    LogUtils.w(response);
                    mData.clear();
                    if (!TextUtils.isEmpty(response) && isGoodJson(response)) {
                        List<MessageObserver> sellerObservers = JSON.parseArray(response, MessageObserver.class);
                        mData.addAll(sellerObservers);
                        refreshNumView();
                        mAdapterRank.notifyDataSetChanged();
                        mRecyclerView.refreshComplete();
                    } else {
                        showToast("数据错误");
                    }

                }
            });
        } else {

        }

    }
*/
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEventRefresh(Event_Send_Message event) {
        if (event.isRefresh()) {
            final String uname = SPUtils.getString(Constants.username, "");
//        RealmResults<RecordEntity> recordEntities = mRealm.where(RecordEntity.class).equalTo("name",uname).findAll();
//        mRecordData = recordEntities;
            mRecordData.clear();
            mRecordData.addAll(JSON.parseArray(mCache.getAsString(uname),RecordEntity.class));
            mAdapterRecord.notifyDataSetChanged();
            mRecyclerView.refreshComplete();

        }
    }

    /**
     * 删除手机号码
     */
    private void deleteObserver(int id) {

        OkHttpUtils.post().url(Constants.deleteObserver)
                .addParams("id", String.valueOf(id))
                .build()
                .execute(new StringCallback() {
                    @Override
                    public void onError(Call call, Exception e, int id) {
                        //结束时别忘了hideDialog（）;
                        hidePDialog();
                        showToast(e.getMessage());
                    }

                    @Override
                    public void onResponse(String response, int id) {
                        //结束时别忘了hideDialog;
                        hidePDialog();
                        LogUtils.e(response);
                        if (!TextUtils.isEmpty(response) && isGoodJson(response)) {
                            showToast("删除成功");
                    //        getData();
                        } else {
                            //error
                            showToast("删除失败~");
                        }
                    }
                });

    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        // TODO: inflate a fragment view
        View rootView = super.onCreateView(inflater, container, savedInstanceState);
        unbinder = ButterKnife.bind(this, rootView);
        return rootView;
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
    }
  /*  @OnClick({R.id.btn_bottom, R.id.tv_date_month, R.id.tv_date_year, R.id.tv_totoday, R.id.logcontent_info})
    void onClick(View view) {
        switch (view.getId()) {

            case R.id.btn_bottom:
                //跳到新建页面
                startActivity(NewJoblogActivity.class);
            default:

                break;
        }
    }
*/

    /*private void parseJsonString(String response) {

        JSONObject jsonObject = JSON.parseObject(response);
        String resCode = jsonObject.getString("resCode");
        String resMsg = jsonObject.getString("resMsg");
        if ("0".equals(resCode)) {
            if (null != dataList && dataList.size() > 0) {
                dataList.clear();
            }

            String obj = jsonObject.getString("obj");
            if (!TextUtils.isEmpty(obj)) {
                OneMonthJournalEntity entity = JSON.parseObject(obj, OneMonthJournalEntity.class);
                setData(entity.getJournal(), entity.getList());
            }
        } else {
            showToast(resMsg);
            VerificateFailedUtil.alertServerError2Login(context, resMsg);
        }
    }

    private void getData(int year, int month) {
        final String uname = SPUtils.getString(Constants.username, "");

        if (RxNetUtils.isAvailable(context)) {
            LogUtils.w("pageNo: " + pageNo);
            String akey = SPUtils.getString(Constants.accessKey, "");
            OkHttpUtils.post().url(Constants.one_month_journal)
                    .addParams(Constants.username, uname)
                    .addParams(Constants.accessKey, akey)
                    .addParams("month", String.valueOf(month))
                    .addParams("year", String.valueOf(year))
                    .build().execute(new StringCallback() {
                @Override
                public void onError(Call call, Exception e, int id) {
                    LogUtils.e(e.getMessage());

                }

                @Override
                public void onResponse(String response, int id) {
                    LogUtils.w(response);

                    if (!TextUtils.isEmpty(response) && isGoodJson(response)) {
                        parseJsonString(response);
                    } else {

                    }

                }
            });
        } else {

        }

    }

    private void setData(OneMonthJournalEntity.JournalBean journal, List<OneMonthJournalEntity.ListBean> list) {

    }*/

}
